package me.lxw.blogsystem.utils;

import java.io.InputStream;
import java.util.Properties;

/**
 * 配置文件解析工具
 * 
 * @author 梁兴威
 *
 */
public class PropertiesUtil {

	private static Properties prop = new Properties();

	/**
	 * 获取配置文件内的值
	 * 
	 * @param filename
	 * @return
	 * @throws Exception
	 */
	public static Properties getProperties(String filename) throws Exception {
		if (filename != null && !filename.equals("")) {
			InputStream fis = Thread.currentThread().getContextClassLoader().getResourceAsStream(filename);
			prop.load(fis);
			fis.close();
			return prop;
		}
		return null;
	}

	/**
	 * 读取配置文件的参数
	 * 
	 * @param propName
	 * @return properties
	 * @throws Exception
	 */
	public static Properties readProperties(String propName) {
		Properties properties = null;
		try {
			properties = new Properties();
			ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
			InputStream inStream = classLoader.getResourceAsStream(propName);
			if (inStream != null) {
				properties.load(inStream);
				inStream.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return properties;
	}

	/**
	 * 获取配置文件中的特定参数的值
	 * 
	 * @param fileName
	 * @param propName
	 * @return String
	 */
	public static String getProperty(String fileName, String propName) {
		Properties properties = readProperties(fileName + ".properties");
		if (properties != null) {
			return (String) properties.get(propName);
		}
		return "";
	}

	/**
	 * 获取配置文件中的特定参数的值
	 * 
	 * @param fileName
	 * @param propName
	 * @param defaultValue
	 * @return long
	 */
	public static long getLongProperty(String fileName, String propName, long defaultValue) {
		String value = getProperty(fileName, propName);
		if (value == null || "".equals(value.trim())) {
			return defaultValue;
		}
		return Long.valueOf(value);
	}

	/**
	 * 获取配置文件中的特定参数的值
	 * 
	 * @param fileName
	 * @param propName
	 * @param defaultValue
	 * @return int
	 */
	public static int getIntProperty(String fileName, String propName, int defaultValue) {
		String value = getProperty(fileName, propName);
		if (value == null || "".equals(value.trim())) {
			return defaultValue;
		}
		return Integer.valueOf(value);
	}

	/**
	 * 获取配置文件中的特定参数的值
	 * 
	 * @param fileName
	 * @param propName
	 * @param defaultValue
	 * @return boolean
	 */
	public static boolean getBooleanProperty(String fileName, String propName, boolean defaultValue) {
		String value = getProperty(fileName, propName);
		if (value == null || "".equals(value.trim())) {
			return defaultValue;
		}
		return Boolean.valueOf(value);
	}

}
